package com.yuantong.xyerp.rest.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.yuantong.xyerp.core.api.common.Constant;
import com.yuantong.xyerp.core.api.dto.MerchantDto;
import com.yuantong.xyerp.core.api.form.QueryForm;
import com.yuantong.xyerp.core.api.model.Category;
import com.yuantong.xyerp.core.api.model.base.RestResponseModel;
import com.yuantong.xyerp.core.api.service.IAreaService;
import com.yuantong.xyerp.core.api.service.ICategoryService;
import com.yuantong.xyerp.core.api.service.IMerchantService;
import com.yuantong.xyerp.core.provider.dao.CategoryMapper;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * S-供应商；P-采购商；A-代理商
 * Created by Jianguo.Yin on 2021-08-03.
 */
@Slf4j
@RestController
@RequestMapping("/merchant")
@Api(tags = "往来单位（供应商、客户、代理商）管理")
public class MerchantController {

    @Autowired
    private IMerchantService merchantService;

    @Resource
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IAreaService areaService;


    // 关于自定义导出数据, 前端传dto
    @ApiOperation(value = "导出往来单位",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export", produces = "application/octet-stream;charset=utf-8")
    public void exportMerchant(HttpServletResponse response,
                               @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        List<MerchantDto> list = merchantService.findByFuzzy(queryForm.getMerchantType(), queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(),queryForm.getIds());

        for (MerchantDto merchantDto : list) {
            //todo 地区 code
            List<String> areaCode = new ArrayList<>();
            areaCode.add(merchantDto.getProvinceId());
            areaCode.add(merchantDto.getCityId());
            areaCode.add(merchantDto.getAreaId());

            merchantDto.setAreaAddress(areaService.findAreaNameByCodes(areaCode).toString() + merchantDto.getAddress());
            // log.info("AreaAddress:{}",merchantDto.getAreaAddress());
            if(merchantDto.getCategoryCodeList() == null || merchantDto.getCategoryCodeList().equals("")) {
                /**
                 * 全部种类  获得所有code与品类名,然后将长度>2的code去掉,这样就只留下大类, 再根据大类code找到品类名
                 */
                List<Category> bigCategory = categoryService.getCategoryByLevel(Constant.BIG_CATEGORY);

                List<String> names = new ArrayList<>();
                for (Category category : bigCategory) {
                    names.add(category.getName());
                }
                merchantDto.setCategoryNames(names.toString());
                continue;
            }
            // 通过串联的大类 codeList 获得每个大类 code 的集合
            String codes = merchantDto.getCategoryCodeList();
            List<String> codeList = new ArrayList<>();
            int flag = 0;
            for (int i = 0; i < codes.length(); i++) {
                if (((i + 1) % 2) == 0) {
                    codeList.add(codes.substring(flag,i + 1));
                    flag = i + 1;
                }
            }
            // 手动添加 categoryName
            List<String> categorieNames = categoryMapper.findByCategoryCodeList(codeList);
            merchantDto.setCategoryNames(categorieNames.toString());
        }

        List<ExcelExportEntity> entity = new ArrayList<>();
        ExcelExportEntity exportEntity = new ExcelExportEntity("创建时间", "createTime", 40);
        exportEntity.setFormat("yyyy-MM-dd hh:mm");

        ExcelExportEntity exportEntity1 = new ExcelExportEntity("往来单位编号", "number",40);
        ExcelExportEntity exportEntity1S = new ExcelExportEntity("供应商编号", "number",40);
        ExcelExportEntity exportEntity1P = new ExcelExportEntity("采购商编号", "number",40);
        ExcelExportEntity exportEntity1A = new ExcelExportEntity("代理商编号", "number",40);

        ExcelExportEntity exportEntity2 = new ExcelExportEntity("往来单位名称", "name",40);
        ExcelExportEntity exportEntity2S = new ExcelExportEntity("供应商名称", "name",40);
        ExcelExportEntity exportEntity2P = new ExcelExportEntity("采购商名称", "name",40);
        ExcelExportEntity exportEntity2A = new ExcelExportEntity("代理商名称", "name",40);

        // easypoi 导出集合?  解决办法: 暂时不用集合, 实际上用string更合适

        ExcelExportEntity exportEntity3 = new ExcelExportEntity("往来单位类型", "categoryNames",40);
        ExcelExportEntity exportEntity3S = new ExcelExportEntity("供应商类型", "categoryNames",40);
        ExcelExportEntity exportEntity3P = new ExcelExportEntity("采购商类型", "categoryNames",40);
        ExcelExportEntity exportEntity3A = new ExcelExportEntity("代理商类型", "categoryNames",40);


        ExcelExportEntity exportEntity4 = new ExcelExportEntity("地区", "areaAddress",40);
        ExcelExportEntity exportEntity5 = new ExcelExportEntity("联系人姓名", "contactsName",40);
        ExcelExportEntity exportEntity6 = new ExcelExportEntity("手机号码", "contactsMobile",40);
        ExcelExportEntity exportEntity7 = new ExcelExportEntity("运维人员", "operatorName",40);
        ExcelExportEntity exportEntity8 = new ExcelExportEntity("状态", "status",40);
        exportEntity8.setReplace(new String[]{"启用_1","停用_0"});

        if (queryForm.getMerchantType() == null){
            queryForm.setMerchantType("default");
        }

        String fileName;

        entity.add(exportEntity);
        switch (queryForm.getMerchantType()) {
            case "S":
                fileName = "供应商列表";
                entity.add(exportEntity1S);
                entity.add(exportEntity2S);
                entity.add(exportEntity3S);
                break;
            case "P":
                fileName = "采购商列表";
                entity.add(exportEntity1P);
                entity.add(exportEntity2P);
                entity.add(exportEntity3P);
                break;
            case "A":
                fileName = "代理商列表";
                entity.add(exportEntity1A);
                entity.add(exportEntity2A);
                entity.add(exportEntity3A);
                break;
            default:
                fileName = "往来单位列表";
                entity.add(exportEntity1);
                entity.add(exportEntity2);
                entity.add(exportEntity3);
                break;
        }
        entity.add(exportEntity4);
        entity.add(exportEntity5);
        entity.add(exportEntity6);
        entity.add(exportEntity7);
        entity.add(exportEntity8);

        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("往来单位表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //
    // @ApiOperation(value = "导入往来单位数据")
    // @ApiImplicitParams({@ApiImplicitParam(name="file",value = "上传文件",dataType = "MultipartFile")})
    // @PostMapping(value = "/import")
    // public RestResponseModel importEmployee(MultipartFile file){
    //     ImportParams params = new ImportParams();
    //     //去掉标题行
    //     params.setTitleRows(1);
    //
    //     try {
    //
    //         List<UserDto> list = ExcelImportUtil.importExcel(file.getInputStream(), UserDto.class, params);
    //
    //         for (int i = list.size()-1; i >=0; i--) {
    //             UserDto user = list.get(i);
    //             // 解决导出的表的问题: Excel 的 cell 的大小和默认导出的cell大小相同时, 会导致 poi 认为Excel 在这一行是数据的,
    //             // 解决方案: 可用 if 去除list中的这条空数据, 判断关键信息是否为 null,  null 就去除这条数据
    //             if (user.getLoginName() != null){
    //                 // 手动增加 uuid
    //                 user.setId(UUID.randomUUID().toString().replaceAll("-",""));
    //                 // 设置默认密码
    //                 user.setPassword("12345678");
    //                 // 解决关联关系, 如excel中是 部门名称, 要转为 RoleId 存入 UserDto
    //                 user.setRoleId(roleService.findRoleByUser(user).getId());
    //                 user.setOrganizationId(organizationService.findOrganizationByName(user).getId());
    //                 continue;
    //             }
    //             list.remove(i);
    //         }
    //         if (userService.saveBatchByUserDtos(list) != 0){
    //             return RestResponseModel.SUCCESS(EnumMsgCode.MSG_SUCCESS);
    //         }
    //         throw new YuantongException(EnumMsgCode.UPLOAD_ERROR);
    //
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //     throw new YuantongException(EnumMsgCode.UPLOAD_ERROR);
    // }
}
